import fsp from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
import fs from "node:fs";
import child_process from "node:child_process";

const __dirname = fileURLToPath(new URL(".", import.meta.url));
const projectRoot = path.resolve(__dirname, "../");
const nodeModulesBin = path.resolve(projectRoot, "node_modules/.bin");

const distDir = path.resolve(projectRoot, "dist");
const distElectronDir = path.resolve(projectRoot, "dist-electron");

const rmdir = async dir => {
  if (fs.existsSync(dir)) {
    await fsp.rm(dir, { recursive: true, force: true });
  }
};

async function prebuild() {
  // 删除dist目录
  await rmdir(distDir);
  await rmdir(distElectronDir);

  const buildCmds = [
    // 下载图标
    ["node", [path.resolve(__dirname, "download-iconfont.mjs")]],
    // ...
  ];

  for (const it of buildCmds) {
    const p = child_process.spawnSync(it[0], it[1] || [], {
      stdio: "inherit",
      cwd: projectRoot,
      env: {
        ...process.env,
        PATH: [nodeModulesBin, process.env.PATH].join(path.delimiter),
      },
    });
    if (p.error) {
      console.error(p.error);
      return process.exit(1);
    }
  }
}

(async () => {
  await prebuild();
})();
